/*- coding = utf-8 -*-
@Time : 2023/3/12 16:20
@Author : CSDN 沉默小管
@File : useClass.ts
@web  : golangblog.blog.csdn.net
@Software: WebStorm
*/
import {App, createApp} from "vue";
import {useIntersectionObserver} from "@vueuse/core";
import errorSvg from "./assets/img/error.svg"
import loading from "./assets/img/loading.gif"
import "./assets/css/base.less"
import "./assets/fonts/iconfont.css"
import imgComponents from "./src/imageLazy.vue"

interface optionsInterface {
    loadingGif?:string
    errorImg?:string
}
const imgDirective = (app:App,options?:optionsInterface)=>{
    let imgOptions={
        loadingGif:options?.loadingGif??loading,//加载gif动图
        errorImg:options?.errorImg??errorSvg,//错误图片自定义
    }
    //判断图片是否存在
    const handleCheckImgExists = (imgObj,imgUrl:string):Promise<boolean> => {
        return new Promise(function(resolve, reject) {
            imgObj.src = imgUrl
            //图片加载完成
            imgObj.onload = function(res) {
                resolve(true)
            }
            //图片加载错误
            imgObj.onerror = function(err) {
                imgObj.src = imgOptions.errorImg
                reject(false)
            }
        })
    }
    app.directive("img-lazy",{
        //数据挂载和渲染完成
        mounted(el, binding) {
            let {value} = binding
            let curEl = el;//当前元素
            curEl.src = imgOptions.loadingGif;

            //监听元素是否在可视窗口
            const {stop} = useIntersectionObserver(curEl,async ([{ isIntersecting }], observerElement)=>{
                //当监听的元素成功进入视口区域，isIntersecting为true
                if(isIntersecting){
                    // 主动停止检测元素可见性
                    stop()
                    await handleCheckImgExists(curEl, value).catch(err=>err)
                }
            },{ threshold: 0 })
        },
        deep:true
    })
}

export {
    imgComponents,imgDirective
}
